<template>
  <el-checkbox-group v-model="checkeds">
    <el-checkbox-button :label="item.value" v-for="(item, index) in options" :key="index + '.custom-checkbox-group'">{{ item.label }}</el-checkbox-button>
  </el-checkbox-group>
</template>

<script setup>
import { toRaw, toRefs, watch, watchEffect } from 'vue';

const emits = defineEmits(['update:values', 'change']);
const props = defineProps({
  options: {
    type: Array,
    default: [{ label: "全部", value: "all" }],
  },
  // 选中的checkbox的value
  values: {
    type: Array,
    default: [],
  },
});
const checkeds = ref([]);
watchEffect(()=>{
    checkeds.value = props.values
})
// checkbox全选的逻辑
watch(
  () => checkeds.value,
  (newValue, oldValue) => {
    const AllLength = props.options.length;
    const AllValues = props.options.map((item) => item.value);
    const allV = 'all';

    const newV = toRaw(newValue);
    const oldV = toRaw(oldValue);
    const isCheckedOld = oldV.includes(allV);
    const isCheckedNew = newV.includes(allV);
    if (isCheckedOld && !isCheckedNew) {
      // 取消了全部
      checkeds.value = [];
    } else if (!isCheckedOld && isCheckedNew) {
      // 点了全部
      checkeds.value = AllValues;
    }
    if (isCheckedOld && isCheckedNew && newV.length != AllLength) {
      // 点了其它
      const i = checkeds.value.findIndex((value) => value === allV);
      checkeds.value.splice(i, 1);
    }
    if (!isCheckedOld && newV.length == AllLength - 1) {
      // 逐个点了全部
      checkeds.value = AllValues;
    }
    const newArr = toRaw(checkeds.value)
    emits("update:values", newArr);
    emits("change", newArr);
  }
);
</script>